<?php


namespace app\partneradmin\controller;


use app\common\controller\partneradmin\Base;
use super\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\partneradmin\model\Partner;
use app\partneradmin\model\CustomerServiceGroup;
use app\partneradmin\model\PartnerAdmin;
use app\partneradmin\model\AppBase;

class Customerservicepersonnel extends Base
{
    protected $noNeedLogin = [];

    protected $model;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\partneradmin\model\CustomerServicePersonnel();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $customerServiceGroupId = $this->request->post('customer_service_group_id', '');

            $phone = $this->request->post('phone', '');
            $name = $this->request->post('name', '');
            $pid = $this->request->post('pid', '');
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $partner_id = $this->admin['partner_id'];
            $where['partner_id'] = $partner_id;
            $adminCustomerServiceInfo = $this->getCustomerServiceInfo();
            if ($this->admin['rule'] == 1) {
                $customerServiceGroupId = $adminCustomerServiceInfo['customer_service_personnel_info']['customer_service_group_id'];
            }
            if ($customerServiceGroupId != '') {
                $where['customer_service_group_id'] = $customerServiceGroupId;
            }
            if ($name != '') {
                $where['name'] = ['like', '%' . $name . '%'];
            }
            if ($phone != '') {
                $where['phone'] = ['like', '%' . $phone . '%'];
            }
            if ($pid != '') {
                $where['pid'] = $pid;
            }
            $where['is_del'] = 0;
            //获取所有合作方
            $partner = new Partner();
            $partnerList = $partner->getPartnerAll([], 'id,name');
            $partnerList = array_column($partnerList, null, 'id');
            //根据条件获取所有客服组
            $customerServiceGroup = new CustomerServiceGroup();
            $customerServiceGroupWhere = [];
            $where['partner_id'] = $partner_id;
            $customerServiceGroupWhere['partner_id'] = $partner_id;
            $customerServiceGroupList = $customerServiceGroup->getCustomerServiceGroupAll($customerServiceGroupWhere, 'id,name');
            $customerServiceGroupList = array_column($customerServiceGroupList, null, 'id');
            $list = $this->model
                ->field('*')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select()
                ->toArray();
            foreach ($list as $key => $value) {
                $value['partner_name'] = empty($partnerList[$value['partner_id']]) ? '' : $partnerList[$value['partner_id']]['name'];
                $value['customer_service_group_name'] = empty($customerServiceGroupList[$value['customer_service_group_id']]) ? '' : $customerServiceGroupList[$value['customer_service_group_id']]['name'];
                //显示每日可分配跟已分配
                //取出所有客服组下的客服账号
                $accountModel = new \app\partneradmin\model\CustomerServiceAccount();
                $accountList = $accountModel->with(['CustomerServiceAccountMiddle'])->where([
                    'customer_service_personnel_id' => $value['id'],
//                    'status' => 1,
                    'switch' => 1
                ])
                    ->select();
                $value['assigned_user_num'] = Statistics::getAssignedUserNum($accountList);
                $list[$key] = $value;
            }
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 重构详情方法
     * @param string $ids
     */

    public function details($ids = "")
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('未查询到数据！', '', [], 404);
        }
        //通过人员查找登陆账号
        $partneradmin = new PartnerAdmin();
        $partneradminInfoWhere = [
            'id' => $row['partner_admin_id']
        ];
        $partneradminInfo = $partneradmin->where($partneradminInfoWhere)->find();
        if (empty($partneradminInfo)) {
            $this->error('获取客服人员登陆信息失败');
        }
        $row['partner_admin_id'] = $partneradminInfo['id'];
        $row['username'] = $partneradminInfo['username'];
        $this->success('详情数据', '', $row);
    }

    /**
     * 根据合作方id+客服组id获取客服人员列表
     * @param null $partner_id
     * @param null $customer_service_group_id
     */
    public function getServicePersonnelListById($partner_id = null, $customer_service_group_id = null, $is_group_leader = 0)
    {
        if (empty($partner_id) || empty($customer_service_group_id)) {
            $this->error('查找失败,参数不合法');
        }
        $where = [
            'customer_service_group_id' => $customer_service_group_id,
            'partner_id' => $partner_id,
            'is_del' => 0,
            'pid' => ['gt', 0]
        ];
        if ($is_group_leader == 0) {
            $where['pid'] = 0;
        }
        $list = $this->model
            ->field('id,name')
            ->where($where)
            ->select()
            ->toArray();
        $data = [
            'list' => $list
        ];
        $this->success('列表', '', $data);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->admin['rule'] == 1) {
            $this->error('无权限!');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();

                try {
//                    是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    //进行逻辑处理
                    //判断该组是否有组长
                    $where = [
                        'customer_service_group_id' => $params['customer_service_group_id'],
//                        'partner_id' => $params['partner_id'],
                        'pid' => 0,
                        'is_del' => 0
                    ];
                    $info = $this->model->where($where)->find();
//                    $rule = 0;
                    //TODO暂时一个客服组只有一个组长 暂时不需要前端传pid
//                    if (empty($params['pid']) && $info) {
//                        $this->error('添加失败,该组已有组长');
//                    } else {
//                        $rule = 1;
//                    }
                    if (empty($info)) {
                        $this->error('添加失败,请先添加客服组组长');
                    }
                    $params['partner_id'] = $info['partner_id'];
                    $rule = 2;

                    $partnerInfo = Partner::get($params['partner_id']);
                    if (!$partnerInfo) {
                        $this->error('不存在的合作方数据');
                    }
                    //检查客服组是否有可分配数量
                    if (!empty($params['distribution_user_num'])) {
                        $customerServiceGroup = CustomerServiceGroup::get($params['customer_service_group_id']);
                        $assignedNum = $this->model->where('customer_service_group_id', '=', $params['customer_service_group_id'])->sum('distribution_user_num');
                        $surplusNum = $customerServiceGroup['distribution_user_num'] - $assignedNum;
                        if ($params['distribution_user_num'] > $surplusNum) {
                            $this->error('客服组剩余可分数为' . $surplusNum);
                        }
                    }
                    //添加客服人员登录账号
                    $salt = Random::alnum();
                    $setpartneradminData = [
                        'username' => $params['username'],
                        'partner_id' => $params['partner_id'],
                        'rule' => $rule,
                        'salt' => $salt,
                        'password' => md5(md5($params['password']) . $salt),
                        'admin_id' => $this->admin['id'],
                        'create_time' => time(),
                    ];
                    //查询登陆账号是否存在
                    $partneradmin = new PartnerAdmin();
                    $partneradminInfo = $partneradmin->where('username', '=', $setpartneradminData['username'])->find();
                    if ($partneradminInfo) {
                        $this->error('添加失败,登录账号已存在');
                    }
                    $partneradminId = $partneradmin->insertGetId($setpartneradminData);

                    //添加客服人员
                    $params['pid'] = $info['id'];
                    $setData = [
                        'name' => $params['name'],
                        'phone' => $params['phone'],
                        'email' => empty($params['email']) ? '' : $params['email'],
                        'pid' => empty($params['pid']) ? 0 : $params['pid'],
                        'customer_service_group_id' => $params['customer_service_group_id'],
                        'partner_admin_id' => $partneradminId,
                        'partner_id' => $params['partner_id'],
                        'distribution_user_num' => empty($params['distribution_user_num']) ? 0 : $params['distribution_user_num'],
                    ];
                    $result = $this->model->save($setData);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }

            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 重构编辑方法
     * @param null $ids
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('不存在的数据', '', [], 404);
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.edit';
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    //检查客服组是否有可分配数量
                    if (!empty($params['distribution_user_num'])) {
                        $customerServiceGroup = CustomerServiceGroup::get($params['customer_service_group_id']);
                        $assignedNum = $this->model->where('customer_service_group_id', '=', $params['customer_service_group_id'])->where('id', 'neq', $ids)->sum('distribution_user_num');
                        $surplusNum = $customerServiceGroup['distribution_user_num'] - $assignedNum;
                        if ($params['distribution_user_num'] > $surplusNum) {
                            $this->error('客服组剩余可分数为' . $surplusNum);
                        }
                    }
                    $setData = [
                        'name' => $params['name'],
                        'phone' => $params['phone'],
                        'email' => empty($params['email']) ? '' : $params['email'],
                        'distribution_user_num' => empty($params['distribution_user_num']) ? 0 : $params['distribution_user_num'],
                        'customer_service_group_id' => $params['customer_service_group_id']
                    ];
                    $result = $row->allowField(true)->isUpdate(true)->save($setData);
                    if (!empty($params['password'])) {
                        $partneradmin = PartnerAdmin::get($row['partner_admin_id']);
                        $params['password'] = md5(md5($params['password']) . $partneradmin->salt);
                        $partneradmin->save(['password' => $params['password']]);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 删除（软删）
     */
    public function del($ids = "")
    {
        $this->error('禁止删除！');
    }

    /**
     * 根据客服id 查看分配人数详情
     */
    public function getDistributionUserDetail()
    {
        $type = $this->request->post("type");
        $ids = $this->request->post("ids");
        switch ($type) {
            case 1:
                $where = [
                    'partner_id' => $ids,
                ];
                break;
            case 2:
                $where = [
                    'customer_service_group_id' => $ids,
                ];
                break;
            case 3:
                $where = [
                    'customer_service_personnel_id' => $ids,
                ];
                break;
        }
        //取出所有应用列表
        $appBaseList = AppBase::select()->toArray();
        $list = [];
        foreach ($appBaseList as $value) {
            $where['app_base_id'] = $value['id'];
            //取出所有客服组下的客服账号
            $accountModel = new \app\admin\model\CustomerServiceAccount();
            $accountList = $accountModel->with(['CustomerServiceAccountMiddle'])->where($where)
                ->select();

            $assigned_user_num = Statistics::getAssignedUserNum($accountList);
            $list[] = [
                'app_base_title' => $value['title'],
                'assigned_user_num' => $assigned_user_num
            ];
        }
        $this->success('操作成功', '', $list);
    }
}